package com.araaya.eslimsmobile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AnalogClock;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.araaya.eslimsmobile.util.ElandConstant;
import com.google.android.gms.maps.CameraUpdateFactory;
/*import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;*/
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;

public class MyMapViewerAdjacentLand extends FragmentActivity implements OnMarkerClickListener{

	/*private MapView mapView;
	private MapController mapController;
	private GeoPoint geoPoint;
	private String coordinate;
	private Projection projection;*/
	private MyItemizedOverlayAdjacentLand itemizedOverlayAdjacentLand;
	private GoogleMap mMap;
	
	
	
	private double array[][];

	private TextView txtSatelliteViewType;
	private TextView txtMapViewType;
	private String coordinate;
	private Marker lastMarker;
	private ArrayList<Marker> markerList = new ArrayList<Marker>();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	
		setContentView(R.layout.map_view_new_adjacent_land);
		setUpMapIfNeeded();
		txtMapViewType = (TextView) findViewById(R.id.txtMapViewType);
		txtSatelliteViewType = (TextView) findViewById(R.id.txtSatelliteViewType);

		txtMapViewType.setTextColor(Color.WHITE);
		txtSatelliteViewType.setTextColor(Color.BLACK);
		mMap.setOnMarkerClickListener(this);
		// click the map taye
		txtMapViewType.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				txtMapViewType.setTextColor(Color.WHITE);
				txtSatelliteViewType.setTextColor(Color.BLACK);
				mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
				
			}
		});

		// click the Satellite type
		txtSatelliteViewType.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				txtSatelliteViewType.setTextColor(Color.WHITE);
				txtMapViewType.setTextColor(Color.BLACK);
				mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

			}
		});
		

		final Button btnExitMap = (Button) findViewById(R.id.btnExitMap);

		// Close Map Button -- Close the map Map
		btnExitMap.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		final Button btnAdjacentMap = (Button) findViewById(R.id.btnAdjacentMap);

		// Adjacent Map Button -- Create Adjacent Map
		btnAdjacentMap.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(),
						LocationMapper.class);
				startActivity(i);
				finish();
			}
		});
		
	

/*		mapView = (MapView) findViewById(R.id.mapview);

		// get the coordinate value
		coordinate = getIntent().getExtras().getString("coordinate");

		// sets the zoom to see the location closer
		mapView.getController().setZoom(20);

		// this will let you to zoom in or out using the controllers
		mapView.setBuiltInZoomControls(true);
		// mapView.setSatellite(true);

		List<Overlay> mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
		projection = mapView.getProjection();

		itemizedOverlayAdjacentLand = new MyItemizedOverlayAdjacentLand(
				drawable, this);

		if (setPoints(coordinate) != null) {
			mapOverlays.add(setPoints(coordinate));
			mapOverlays.add(new MyOverlay());
		}*/
		
coordinate = getIntent().getExtras().getString("coordinate");
		
		

		// sets the zoom to see the location closer
		/*mapView.getController().setZoom(20);

		// this will let you to zoom in or out using the controllers
		mapView.setBuiltInZoomControls(true);
		// mapView.setSatellite(true);

		List<Overlay> mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
		projection = mapView.getProjection();

		itemizedoverlay = new MyItemizedOverlay(drawable, this);*/
        PolygonOptions polyOptions= new PolygonOptions();
        MarkerOptions mOptions = new MarkerOptions();
		mOptions.flat(true);
		mOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
		
      
		if (setPoints(coordinate) != null) {
			polyOptions =setPoints(coordinate);
			polyOptions.strokeWidth(5);
		
			Polygon pg=mMap.addPolygon(polyOptions);
			for(LatLng e : polyOptions.getPoints()){
		   Marker marker= mMap.addMarker(mOptions.position(e));
		
			}
		
		}
		for (LatLng p: polyOptions.getPoints()) {
			Log.d("options: ", "polygon: lat: "+p.latitude+"lng: "+p.longitude);
		}

		CameraPosition position = new CameraPosition.Builder().target(polyOptions.getPoints().get(0))
				.zoom(50).build();
		mMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));

	}

/*	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}*/

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_mapview_adjacent_land, menu);

		return super.onCreateOptionsMenu(menu);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuUndo:
			int pointSize = KmlHome.pointList.size();
			if (pointSize > 0) {
				undoPointAlert(ElandConstant.UNDO_POINT_MSG_STR,
						ElandConstant.UNDO_POINT_TITLE_STR, "Yes",
						R.drawable.deletepoint);
			} else {
				Toast.makeText(this, ElandConstant.UNDO_POINT_FAILD_STR,
						Toast.LENGTH_LONG).show();
			}
			return true;
		case R.id.help:
			Intent i = new Intent(getBaseContext(),
					HelpActivity.class);
			i.putExtra("from", "AdjecentLand");
			startActivity(i);
			return true;

		}
		return false;
	}

	private PolygonOptions setPoints(String values) {
		PolygonOptions p = null ;
		try {
			StringTokenizer stringTokenizer = new StringTokenizer(values);

			array = new double[stringTokenizer.countTokens()][3];
			int arrayCount = 0;
			double lat = 0;
			double lon = 0;
			float alt = 0;
			p = new PolygonOptions();
			while (stringTokenizer.hasMoreTokens()) {
				String firstToken = stringTokenizer.nextToken();

				StringTokenizer stringTokenizer2 = new StringTokenizer(
						firstToken, ",");

				while (stringTokenizer2.hasMoreTokens()) {
					int col = arrayCount % 3;
					int row = arrayCount / 3;

					String secondToken = stringTokenizer2.nextToken();
					array[row][col] = Double.parseDouble(secondToken);
					arrayCount++;

					if (col == 0) {
						lat = Double.parseDouble(secondToken);
					} else if (col == 1) {
						lon = Double.parseDouble(secondToken);
					} else if (col == 2) {
						alt = Float.parseFloat(secondToken);
					}

				}
				

				Log.d("lat==>", "lat==> " + lat);
				Log.d("lon==>", "lon==> " + lon);

				//GeoPoint point = new GeoPoint(lngVal, latVal);
			//	mapView.getController().setCenter(point);
			//	OverlayItem overlayitem = new OverlayItem(point, "", "");

			//	itemizedoverlay.addOverlay(overlayitem);

				p.add(new LatLng(lon, lat));
			}

		} catch (Exception e) {
			Log.d("Exception MyMap", e.getMessage());

		}

		return p;

	}

	// draw the line
	/*class MyOverlay extends Overlay {

		int latVal;
		int lngVal;

		public MyOverlay() {

		}

		public void draw(Canvas canvas, MapView mapv, boolean shadow) {
			super.draw(canvas, mapv, shadow);

			Paint mPaint = new Paint();
			mPaint.setDither(true);
			mPaint.setColor(Color.RED);
			mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
			mPaint.setStrokeJoin(Paint.Join.ROUND);
			mPaint.setStrokeCap(Paint.Cap.ROUND);
			mPaint.setStrokeWidth(2);

			for (int i = 0; i < array.length; i++) {
				latVal = (int) (array[i][0] * 1E6);
				lngVal = (int) (array[i][1] * 1E6);

				GeoPoint gP1 = new GeoPoint(lngVal, latVal);
				if (i == array.length - 1) {
					latVal = (int) (array[0][0] * 1E6);
					lngVal = (int) (array[0][1] * 1E6);
				} else {
					latVal = (int) (array[i + 1][0] * 1E6);
					lngVal = (int) (array[i + 1][1] * 1E6);
				}

				GeoPoint gP2 = new GeoPoint(lngVal, latVal);

				Point p1 = new Point();
				Point p2 = new Point();
				Path path = new Path();

				projection.toPixels(gP1, p1);
				projection.toPixels(gP2, p2);

				path.moveTo(p2.x, p2.y);
				path.lineTo(p1.x, p1.y);

				canvas.drawPath(path, mPaint);

			}

		}

	}*/

	// Undo point Alert
	public void undoPointAlert(String message, String title, String btnTxt,
			Integer image) {

		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(message)
				.setCancelable(false)
				.setPositiveButton(btnTxt,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								int kmlInxToRmv= KmlHome.pointList.size() - 1;
								Double lat = Double.parseDouble(KmlHome.pointList.get(KmlHome.pointList
										.size() - 1).get("lat"));
								Double lon = Double.parseDouble(KmlHome.pointList.get(KmlHome.pointList
										.size() - 1).get("lon"));
								LatLng newPos = new LatLng(lat, lon);
								Marker m= markerList.get(KmlHome.pointList.size() - 1);
								markerList.remove(kmlInxToRmv);
								KmlHome.pointList.remove(kmlInxToRmv);
								Log.d("kml","kml undo: "+KmlHome.pointList.size()+"marker list : "+markerList.size());
								
								
								MarkerOptions mOptions = new MarkerOptions();
								mOptions.flat(true);
								mOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
							//	LatLng newPos = lastMarker.getPosition();
								m.remove();
								mOptions.position(newPos);
								
								
								//lastMarker.remove();
								/*if(KmlHome.pointList.size() >= 1){
									Double lat = Double.parseDouble(KmlHome.pointList.get(KmlHome.pointList
											.size() - 1).get("lat"));
									Double lon = Double.parseDouble(KmlHome.pointList.get(KmlHome.pointList
											.size() - 1).get("lon"));
									LatLng a = new LatLng(lat, lon);
						
								}*/
								Marker marker =mMap.addMarker(mOptions);
								/*markerList.add(marker);*/
								Log.d("kml","kml undo after: "+KmlHome.pointList.size()+"marker list : "+markerList.size());
								return;

							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						dialog.cancel();
						return;

					}
				});

		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(title);
		// Icon for AlertDialog
		alert.setIcon(image);
		alert.show();
	}
	
	
   private void setUpMapIfNeeded() {
        if (mMap != null) {
            return;
        }
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapAdj)).getMap();
        if (mMap == null) {
            return;
        }
        // Initialize map options. For example:
        // mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    }
    
	private void adjacentMapAlert(final Marker marker) {

		try {

			
			final double lat = marker.getPosition().latitude;
			final double lon = marker.getPosition().longitude;
			// Toast.makeText(ctx, toast, Toast.LENGTH_LONG).show();
			String txt = "GPS Point : ";
			txt += " \n Lat : " + lat + " " + "\n Lon : " + lon + ""
					+ "\n\n Do you want to add this point?";

			AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
			alt_bld.setMessage(txt)
					.setCancelable(false)
					.setPositiveButton("Add Point",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									MarkerOptions mOptions = new MarkerOptions();
									mOptions.flat(true);
									mOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.markerblue));
									LatLng newPos = marker.getPosition();
									mOptions.position(newPos);
									
									marker.remove();
									Log.d("PointListSize=", "kml add before"
											+ KmlHome.pointList.size()+" marker;  "+markerList.size());
									
									Marker m=mMap.addMarker(mOptions);
									markerList.add(m);
								//	res=true;
									// Add point
									HashMap<String, String> map = new HashMap<String, String>();
									map.put("lon", "" + lon);
									map.put("lat", "" + lat);
									map.put("alt", "" + 0);
									KmlHome.pointList.add(map);

									String toast = "The Point is added.";
									toast += "\n coordinates AdjacentLand: Lat = "
											+ lat + " Lon = " + lon;

									Log.d("PointListSize=", "kml add"
											+ KmlHome.pointList.size()+" marker;  "+markerList.size());
									toast += "\n Point List Size : "
											+ KmlHome.pointList.size();

									Toast.makeText(MyMapViewerAdjacentLand.this, toast,
											Toast.LENGTH_LONG).show();
									
									
									return;

								}
							})

					.setNeutralButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

									//res=false;
									dialog.cancel();

									return;

								}
							});

			AlertDialog alert = alt_bld.create();
			alert.setTitle("Adjacent Map Point");
			// Icon for AlertDialog
			alert.setIcon(R.drawable.land);
			alert.show();
			
			

		} catch (Exception e) {
			e.printStackTrace();
		}

	}


	@Override
	public boolean onMarkerClick(Marker marker) {
		Log.d("cliuxked", "clicked: " + marker.getPosition().latitude + " :: "
				+ KmlHome.pointList.size()+ "::marker: "+markerList.size());
		int index=0;
		boolean marked = false;
		for (int i = 0; i < KmlHome.pointList.size(); i++) {
			Double lat = Double.parseDouble(KmlHome.pointList.get(i).get("lat"));
			Double lon = Double.parseDouble(KmlHome.pointList.get(i).get("lon"));
			if ((marker.getPosition().latitude == lat) && (marker.getPosition().longitude == lon)) {
				Log.d("clicked", "clicked: " + marker.getPosition().latitude+ " :: " + KmlHome.pointList.size());
				marked = true;
				index=i;
			}
		}

		if (marked) {
			Log.d("Marked", "Marked: " + marker.getPosition().latitude
					+ " :: " + KmlHome.pointList.size());
		//	removePointAlert(marker,index);
			String toast = "Point is already selected";
			Toast.makeText(MyMapViewerAdjacentLand.this, toast,
					Toast.LENGTH_LONG).show();
			
		} else {
			Log.d("PointListSize=", "kml add onclick"
					+ KmlHome.pointList.size()+" marker;  "+markerList.size());
			
			adjacentMapAlert(marker);
		}

		return false;
	}
	
	
	
	public void removePointAlert(final Marker marker,final int index){
		final double lat = marker.getPosition().latitude;
		final double lon = marker.getPosition().longitude;
		// Toast.makeText(ctx, toast, Toast.LENGTH_LONG).show();
		String txt = "GPS Point : ";
		txt += " \n Lat : " + lat + " " + "\n Lon : " + lon + ""
				+ "\n\n Do you want to remove this point?";

		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(txt)
				.setCancelable(false)
				.setPositiveButton("Remove Point",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int id) {
								MarkerOptions mOptions = new MarkerOptions();
								mOptions.flat(true);
								mOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
								LatLng newPos = marker.getPosition();
								mOptions.position(newPos);
								
								marker.remove();
								mMap.addMarker(mOptions);
							//	res=true;
								// Add point
								HashMap<String, String> map = new HashMap<String, String>();
								map.put("lon", "" + lon);
								map.put("lat", "" + lat);
								map.put("alt", "" + 0);
								KmlHome.pointList.remove(index);

								String toast = "The Point is removed.";
								toast += "\n coordinates AdjacentLand: Lat = "
										+ lat + " Lon = " + lon;

								Log.d("PointListSize=", ""
										+ KmlHome.pointList.size());
								toast += "\n Point List Size : "
										+ KmlHome.pointList.size();

								Toast.makeText(MyMapViewerAdjacentLand.this, toast,
										Toast.LENGTH_LONG).show();
								
								
								return;

							}
						})

				.setNeutralButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int id) {

								//res=false;
								dialog.cancel();

								return;

							}
						});

		AlertDialog alert = alt_bld.create();
		alert.setTitle("Adjacent Map Point");
		// Icon for AlertDialog
		alert.setIcon(R.drawable.deletepoint);
		alert.show();
	}

}
